package com.san.andoid.displayinfo;

import java.util.Map;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;

public class DisplayPrefsActivity extends PreferenceActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.prefs);

		setupAppPrefs();

		getPreferenceScreen().setOnPreferenceChangeListener(onPreferenceChangeListener);
		Map<String, ?> map = PreferenceManager.getDefaultSharedPreferences(this.getBaseContext()).getAll();

		for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {

			Preference preference = getPreferenceScreen().getPreference(i);
			if (preference instanceof PreferenceCategory) {
				PreferenceCategory preferenceCategory = (PreferenceCategory) preference;
				for (int j = 0; j < preferenceCategory.getPreferenceCount(); j++) {
					Preference subPreference = ((PreferenceCategory) preference).getPreference(j);
					if (subPreference.getKey() != null)
						subPreference.setSummary(map.get(subPreference.getKey()) + "");

				}
			} else if (preference instanceof Preference) {
				if (preference.getKey() != null)
					preference.setSummary(map.get(preference.getKey()) + "");
			}
		}
	}

	private void setupAppPrefs() {
		SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		if (defaultSharedPreferences.getString(Prefs.sr, null) == null) {
			DisplayMetrics metrics = getResources().getDisplayMetrics();
			Editor editor = defaultSharedPreferences.edit();
			editor.putString(Prefs.sr, metrics.widthPixels + " x " + metrics.heightPixels);
			editor.putFloat(Prefs.dpix, metrics.xdpi);
			editor.putFloat(Prefs.dpiy, metrics.ydpi);
			editor.putFloat(Prefs.sf, metrics.scaledDensity);
			editor.putInt(Prefs.ddpi, metrics.densityDpi);
			editor.commit();
		}

	}

	OnPreferenceChangeListener onPreferenceChangeListener = new OnPreferenceChangeListener() {
		public boolean onPreferenceChange(Preference preference, Object newValue) {
			preference.setSummary(newValue.toString());
			return false;
		}
	};

}
